﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Dependencies;
using Tyche.Common.Resource;

namespace Tyche.WebApiService.DependencyResolver
{
    public class TycheWebApiDependencyResolver : IDependencyResolver
    {
        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {
        }

        public object GetService(Type serviceType)
        {
            if (serviceType.BaseType != typeof(ApiController))
            {
                return null;
            }

            return GetServiceInstance(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (serviceType.BaseType != typeof(ApiController))
            {
                return new List<object>();
            }

            return new List<object>() { GetServiceInstance(serviceType) };
        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        private object GetServiceInstance(Type serviceType)
        {
            return Activator.CreateInstance(serviceType
                , serviceType
                .GetConstructors()
                .First()
                .GetParameters()
                .Select(p => { return TycheResourceManager.CreateInstance(p.ParameterType, true); })
                .ToArray());
        }
    }
}
